############################################### File notes #######################################

############################### Clean workspace and define settings ##############################


### Run script to set up environment
rm(list=ls())


### Load packages if not already installed
install.packages("K:/BE/1261/Cases/Walgreens_Rite Aid_1610026/Research/Brian/Code/Code/R Packages/lfe_2.5-1998.zip", repos = NULL, type = "win.binary")
install.packages("K:/BE/1261/Cases/Walgreens_Rite Aid_1610026/Research/Brian/Code/R Packages/purrr_0.2.4.zip", repos = NULL, type = "win.binary")
install.packages("K:/BE/1261/Cases/Walgreens_Rite Aid_1610026/Research/Brian/Code/R Packages/tidyselect_0.2.3.zip", repos = NULL, type = "win.binary")
install.packages("K:/BE/1261/Cases/Walgreens_Rite Aid_1610026/Research/Brian/Code/R Packages/tidyr_0.7.2.zip", repos = NULL, type = "win.binary")
library(openxlsx)
library(foreign)
library(Matrix)
library(lfe)
library(data.table)
library(sp)
library(maps)
library(maptools)
library(ggplot2)
library(xtable)
library(lattice)
library(survival)
library(Formula)
library(Hmisc)
library(doBy)
library(readr)
library(tools)
library(tidyr)
library(readstata13)

dataIn <- file.path("K:","BE","1257","Projects","Medicare Claims","HospRetro","Drafts","Health_outcomes","FigureCreation","PSPatients","RefereeResponse","MakeTables")

#dataIn has the following files:
 #"death_fe_small.dta"          "death_lim_small.dta"         "diab_fe_small.dta"           "Diab_lim_small.dta"          "femAllBlocks.dta"            "fembetaBlockDiab.dta"        "fembetaDeath.dta"           
 # "fembetaDiab.dta"             "fembetaDiab_overall.dta"     "fembetaHyp.dta"              "fembetaHyp_overall.dta"      "femblockDeath_overall.dta"   "femDiabBlocks.dta"           "femHypBlocks.dta"           
 # "hyp_fe_small.dta"            "Hyp_lim.dta"                 "ll_death_small.dta"          "ll_diab_small.dta"           "ll_hyp_small.dta"            "maleAllBlocks.dta"           "malebetaBlockDeath.dta"     
 # "malebetaBlockHyp.dta"        "malebetaDeath.dta"           "malebetaDiab.dta"            "malebetaDiab_overall.dta"    "malebetaHyp.dta"             "malebetaHyp_overall.dta"     "maleblockDeath_overall.dta" 
 # "maleDiabBlocks.dta"          "maleHypBlocks.dta"           "mbm_death_small.dta"         "mbm_diab_small.dta"          "mbm_hyp_small.dta"           "overall_death_zip_small.dta" "Overall_diab_zip_small.dta" 
 # "Overall_hyp_zip_small.dta"   "PS_YMeans_1_fillin.dta"      "PS_YMeans_2_fillin.dta"      "YMeans_fillin1.dta"          "YMeans_fillin2.dta"


############################################### create functions for later use ################ 
options(scipen = 999)
#Readin function
 fn.readin <- function(x){
   z <- read.dta13(paste0(dataIn,"/",x)) #dta. files
   z$dataname <- as.character(x) #Use the file name to determine sex results 
   z$sex[grepl("1",z$dataname)] <- "Male" #Use the file name to determine sex results 
   z$sex[grepl("2",z$dataname)] <- "Female" #Use the file name to determine sex results 
   z$yvar[z$yvar=="_death"] <-paste0(z$deathvar[z$yvar=="_death"],z$yvar[z$yvar=="_death"])
   z <- z[,c("sampletype","yvar","n","mn","sd","sex","deathvar")]
   z[,c("mn","sd")] <- round(z[,c("mn","sd")],4)
   z$n <- prettyNum(z$n, big.mark=",")
   z$mn <- as.character(z$mn)
   z$sd <- as.character(z$sd)
   names(z) <- c("sampletype","yvar","N","Mean","Standard Deviation","sex","deathvar")
   z <- reshape(z,direction="wide",idvar=c("yvar","sex","deathvar"),timevar="sampletype")
   z$yvar[z$yvar=="1_death"] <- "Mortality"
   z$yvar[z$yvar=="2_death"] <- "Mortality"
   z$yvar[z$yvar=="3_death"] <- "Mortality"
   z$yvar[z$yvar=="acuteicd8"] <- "Acute cardiac"
   z$yvar[z$yvar=="ami"] <- "AMI"
   z$yvar[z$yvar=="ihd"] <- "Ischemic heart"
   z$yvar[z$yvar=="diabcomp1"] <- "Asymptomatic"
   z$yvar[z$yvar=="diabcomp2"] <- "Symptomatic"
   z$yvar[z$yvar=="glaucoma"] <- "Glaucoma"
   names(z$yvar) <- "Outcome"
   return(z)
 }


 #Execute the readin
files_ymean <- dir(dataIn)[grepl("PS_Y*",dir(dataIn))]

y.means <- lapply(files_ymean , fn.readin )

ymeans <- rbindlist(y.means)
ymeans <- as.data.frame(ymeans[order(ymeans$sex,ymeans$deathvar),])
ym <- ymeans[,names(ymeans)[names(ymeans)!="sex" & names(ymeans)!="deathvar"]]  
 names(ym)[1] <- "Outcome"
  
addtorow <- list()
addtorow$pos <- list(0,0,0,1,5,9,10,14)
addtorow$command <- c( "& \\multicolumn{3}{c}{\\textbf{Control Sample} & \\multicolumn{3}{c}{\\textbf{Pre-merger}}& \\multicolumn{3}{c}{\\textbf{Post-merger}}\\\\\n", 
                       paste0(paste(gsub(".[0-9]","",names(ym)),collapse = " & "),"\\\\\n"), 
                                               paste0(paste0("\\textbf{",ymeans$sex[1],"}"),"& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Full Sample}","} \\\\\n"),
                                               paste0("& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Hypertension Sample}","} \\\\\n") ,
                                               paste0("& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Diabetes Sample}","} \\\\\n") ,
                                               paste0(paste0("\\textbf{",ymeans$sex[length(ymeans$sex)],"}"),"& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Full Sample}","} \\\\\n") ,
                                               paste0("& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Hypertension Sample}","} \\\\\n") ,
                                               paste0("& \\multicolumn{",length(ym )-1,"}{c}{","\\underline{Diabetes Sample}","} \\\\\n")  ) 
print(xtable(ym),add.to.row = addtorow,include.colnames = FALSE,include.rownames = FALSE, file=file.path(dataIn,paste0("Table_YMeans.tex")))


